#!/bin/bash

set -e

git_cmd=`which git`
export_dir='{{export-dir}}'
history_dir='{{history-dir}}'
publish_dir='{{publish-dir}}'
git_url='{{remote-url}}'
git_branch='{{remote-branch}}'
partial_update='{{partial-update}}'


echo '###########################################################'
echo '##              Org-webpage upload script                ##'
echo '###########################################################'

echo ''
echo "Export  Directory:    $export_dir"
echo "Publish Directory:    $publish_dir"
echo "History Directory:    $history_dir"

echo ''
echo "Git Remote url:       $git_url"
echo "Git Remote branch:    $git_branch"

echo ''
if [[ $git_branch = "master" ]]
then
    read -p "Type \"branch-name\" to run this upload-script: " -r
    if [[ ! $REPLY = "master" ]]
    then
        exit 1
    fi
else
    read -p 'Run this upload-script? [y/n]' -n 1 -r
    if [[ ! $REPLY = "y" ]]
    then
        exit 1
    fi
fi

echo ''
echo ''
echo '###########################################################'
echo '##  Building history directory ...                       ##'
echo '###########################################################'
$git_cmd clone --depth=1 --branch "$git_branch"  "$git_url" "$history_dir"

echo ''
echo ''
echo '###########################################################'
echo '##  Generate publish directory and git add/commit ...    ##'
echo '###########################################################'

cd "$publish_dir"

cp -r "$history_dir"/.git  "$publish_dir"

$git_cmd config core.autocrlf false

if [[ $partial_update = "yes" ]]
then
    $git_cmd reset --hard
    echo "NOTE: Enable Partial upload, reset to HEAD with command: '$git_cmd reset --hard' ..."
fi

cp -r "$export_dir"/*  "$publish_dir"

$git_cmd add --all .
$git_cmd commit -m 'Update published html files, committed by org-webpage.'
$git_cmd --no-pager diff HEAD~1 --stat

echo ''
echo ''
echo '###########################################################'
echo '## Run git push ...                                      ##'
echo '###########################################################'

read -p "Push to: Remote: $git_url
         Branch: $git_branch?  [y/n] " -n 1 -r

if [[ ! $REPLY = "y" ]]
then
    exit 1
fi

echo ''
$git_cmd push origin $git_branch

echo ''
echo ''
echo 'Press any key to continue...'
read -s -n 1 any_key
exit 0
